import * as postService from '../../services/organize/postService';
import { message } from "antd";
import config from '../../config/config';
import * as departmentService from "../../services/organize/departmentService";

export default {
  namespace: "postModel",
  state: {
    postLoading: false,
    postList: [],
    total: 0,
    currentPage: 1,
    pageSize: config.PAGE_SIZE,
    postModalVisible: false,
    operateType: 'add',
    postInfoData: null,
    selectedRowKeys: [],
    searchParams: null,
  },

  reducers: {
    updateState(state, { payload }) {
      return { ...state, ...payload }
    },
  },

  effects: {
    *getPostPage({ payload: params }, { select, call, put }) {
      yield put({ type: "updateState", payload: { postLoading: true }});
      const { currentPage, pageSize } = yield select(state => state.postModel);
      const res = yield call(postService.getPostPage, { ...params, currentPage, pageSize });
      if (res.code == "200") {
        yield put({
          type: 'updateState',
          payload: { postList: res.data.records, total: res.data.total, currentPage, pageSize },
        });
      }
      yield put({ type: "updateState", payload: { postLoading: false }});
    },

    *addPost({payload: params}, {put, call}) {
      const res = yield call(postService.addPost, params);
      if (res.code == "200") {
        message.info("新增成功！");
        yield put({ type: 'updateState', payload: { postModalVisible: false }});
        yield put({ type: 'getPostPage', payload: {}});
      } else {
        message.info("新增失败！");
      }
    },

    *updatePost({payload: params}, {put, call}) {
      const res = yield call(postService.updatePost, params);
      if (res.code == "200") {
        message.info("修改成功！");
        yield put({ type: 'updateState', payload: { postModalVisible: false }});
        yield put({ type: 'getPostPage', payload: {}});
      } else {
        message.info("修改失败！");
      }
    },

    *deletePost({payload: ids}, {put, call}) {
      const res = yield call(postService.deletePost, ids);
      if (res.code == "200") {
        message.info("删除成功！");
        yield put({ type: 'getPostPage', payload: {}});
      } else {
        message.info("删除失败！");
      }
    },
  },

  subscriptions: {
    setup({ dispatch, history }) {
      const pathname = window.location.pathname;
      console.log("postModel subscriptions setup pathname => ", pathname);
      if (pathname === "/organize/post") {
        dispatch({ type: 'getPostPage', payload: {}});
      }
    },
  },
};
